package com.ai.imagetext.service;

import com.ai.imagetext.dto.*;
import com.ai.imagetext.entity.User;
import com.ai.imagetext.repository.UserRepository;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.Optional;

@Slf4j
@Service
@RequiredArgsConstructor
public class UserService {

    private final UserRepository userRepository;
    private final PasswordEncoder passwordEncoder;

    /**
     * 用户注册
     */
    @Transactional
    public UserDTO register(UserRegisterRequest request) {
        // 验证密码长度
        if (request.getPassword() == null || request.getPassword().length() < 6) {
            throw new IllegalArgumentException("密码长度必须至少6个字符");
        }

        // 检查账号是否已存在
        if (userRepository.existsByUsernameAndIsDeletedFalse(request.getUsername())) {
            throw new RuntimeException("账号已存在");
        }

        // 检查邮箱是否已存在
        if (userRepository.existsByEmailAndIsDeletedFalse(request.getEmail())) {
            throw new RuntimeException("账号已存在");
        }

        // 创建新用户
        User user = new User();
        user.setUsername(request.getUsername());
        user.setPassword(passwordEncoder.encode(request.getPassword()));
        user.setEmail(request.getEmail());
//        user.setNickname(request.getNickname() != null ? request.getNickname() : request.getUsername());
        user.setStatus(1);
        user.setLoginCount(0);

        User savedUser = userRepository.save(user);
        log.info("用户注册成功: {}", savedUser.getUsername());

        return convertToDTO(savedUser);
    }

    /**
     * 用户登录
     */
    @Transactional
    public LoginResponse login(UserLoginRequest request) {
        // 查找用户
        Optional<User> userOpt = userRepository.findByUsernameOrEmailAndIsDeletedFalse(request.getUsernameOrEmail());
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户不存在");
        }

        User user = userOpt.get();

        // 检查用户状态
        if (user.getStatus() != 1) {
            throw new RuntimeException("用户已被禁用");
        }

        // 验证密码
        if (!passwordEncoder.matches(request.getPassword(), user.getPassword())) {
            throw new RuntimeException("密码错误");
        }

        // 更新登录信息
        user.setLastLoginTime(LocalDateTime.now());
        user.setLoginCount(user.getLoginCount() + 1);
        userRepository.save(user);

        // 生成token（这里简化处理，实际项目中应该使用JWT）
        String token = generateToken(user);

        log.info("用户登录成功: {}", user.getUsername());

        return new LoginResponse(token, convertToDTO(user), "登录成功");
    }

    /**
     * 修改密码
     */
    @Transactional
    public void changePassword(Long userId, ChangePasswordRequest request) {
        User user = userRepository.findById(userId)
                .orElseThrow(() -> new RuntimeException("用户不存在"));

        // 验证原密码
        if (!passwordEncoder.matches(request.getOldPassword(), user.getPassword())) {
            throw new RuntimeException("原密码错误");
        }

        // 设置新密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userRepository.save(user);

        log.info("用户修改密码成功: {}", user.getUsername());
    }

    /**
     * 忘记密码 - 直接重置密码
     */
    @Transactional
    public void forgotPassword(ForgotPasswordRequest request) {
        // 查找用户，验证用户名和邮箱都匹配
        Optional<User> userOpt = userRepository.findByUsernameAndIsDeletedFalse(request.getUsername());
        if (userOpt.isEmpty()) {
            throw new RuntimeException("用户名不存在");
        }

        User user = userOpt.get();

        // 验证邮箱是否匹配
        if (!user.getEmail().equals(request.getEmail())) {
            throw new RuntimeException("邮箱与用户名不匹配");
        }

        // 直接重置密码
        user.setPassword(passwordEncoder.encode(request.getNewPassword()));
        userRepository.save(user);

        log.info("用户重置密码成功: {}", user.getUsername());
    }

    /**
     * 根据ID查找用户
     */
    public UserDTO findById(Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("用户不存在"));
        return convertToDTO(user);
    }

    /**
     * 转换为DTO
     */
    private UserDTO convertToDTO(User user) {
        UserDTO dto = new UserDTO();
        BeanUtils.copyProperties(user, dto);
        return dto;
    }

    /**
     * 生成token（简化实现）
     */
    private String generateToken(User user) {
        return "token_" + user.getId() + "_" + System.currentTimeMillis();
    }
}